package com.service.lx;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dao.lx.DeptDAO;
import com.entity.Dept;
import com.utils.DeptVo;
import com.service.ServiceException;


@Service
@Transactional(rollbackFor = Exception.class)
public class DeptService {
	@Autowired
	private DeptDAO deptDAO;
	/**
	 * 添加/修改/逻辑删除
	 * @param dept
	 * @throws ServiceException
	 */
	public void addAndUpdateDept(Dept dept) throws ServiceException{
		try {
			dept.setDeptIntodate(new Date());
			deptDAO.save(dept);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}
	
	/**
	 * 删除
	 * @param deptid
	 * @throws ServiceException
	 */
	public void deleteDept(Long deptid) throws ServiceException{
		try {
			deptDAO.delete(deptid);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}
	/**
	 * 单条查询
	 * @param deptid
	 * @return
	 */
	public Dept findOne(Long deptid) {
		return deptDAO.findOne(deptid);
	}
	
	public List<Dept> findAll() {
		return (List<Dept>) deptDAO.findAll();
	}
	
	/**
	 * 查询所有部门,显示树形
	 * @return
	 */
	public List<DeptVo> listTbDept(){
		List<Dept> list = (List<Dept>) deptDAO.findAll();
		DeptVo deptVo = new DeptVo();
		List<DeptVo> deptVos = new ArrayList<>();
		for(int i = 0;i<list.size();i++) {
			if(list.get(i).getDeptLastid()==null) {
				deptVo.setDeptId(list.get(i).getDeptId());
				deptVo.setDeptName(list.get(i).getDeptName());
				deptVo.setChildren(new ArrayList<>());
				deptVo.setDept(list.get(i));
				deptVos.add(getNode(deptVo,list));
			}
		}
		return deptVos;
	}
	//查找子节点
	private DeptVo getNode(DeptVo deptVo, List<Dept> list) {
		for(int i = 0;i<list.size();i++) {
			if(list.get(i).getDeptLastid()!=null){
				if(deptVo.getDept().getDeptId()==list.get(i).getDeptLastid().longValue()) {
					Dept dept = list.get(i);
					DeptVo deptVo2 = new DeptVo();
					deptVo2.setDeptId(dept.getDeptId());
					deptVo2.setDeptName(dept.getDeptName());
					deptVo2.setChildren(new ArrayList<>());
					deptVo2.setDept(dept);
					deptVo.getChildren().add(getNode(deptVo2,list));
				}
			}
		}
		if(deptVo.getChildren().size()==0) {
			deptVo.setChildren(null);	
		}
		return deptVo;
	}

}
